<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Picture extends Controller_DefaultTemplate{

public function action_index()
{
}

public function action_list()
{
	$booklet_id = $this->request->param('id');
	$picture = ORM::factory('picture');
	if ($booklet_id != NULL)
	{
		$picture->where('booklet_id', '=', $booklet_id);
	}
	$query_result = $picture->find_all();
	$this->template->content = View::factory('book/picture_list');
	$this->template->content->set('booklet_id', $booklet_id);
	$this->template->content->set('picture_list', $query_result->as_array());
}

public function action_add()
{
	$id = $this->request->param('id');
	if ($id != NULL)
	{
		$this->template->content = View::factory('book/picture_add');
		$this->template->content->set("id", $id);
	}
}

public function action_save()
{
	$id = $this->request->param('id');
	if ($_POST)
	{
		foreach ($_POST as $key => $value) 
		{
			$picture = ORM::factory('picture');
			$picture->values(array(
				'booklet_id' => $id,
				'description' => arr::get($_POST, 'description'),
				'image' => $value,
			));
			$picture->save();
		}
		$this->request->redirect('/admin/picture/list/'.$id);
	}
}

public function action_upload()
{
	if (!empty($_FILES)) 
	{
		$tempFile = $_FILES['Filedata']['tmp_name'];
		$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
		$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
		//$fileParts = pathinfo($_FILES['Filedata']['name']);
		//$targetFile =  str_replace('//','/',$targetPath) . md5_file($tempFile). '.' . $fileParts['extension'];
		
		move_uploaded_file($tempFile,$targetFile);
		echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
	}
}

public function action_savelist()
{
	$booklet_id =  arr::get($_POST, 'booklet_id');
	if ($_POST)
	{
		foreach ($_POST as $key => $value)
		{
			$id = $value["id"];
			$description = $value["description"];
			$picture = ORM::factory('picture')->where('id', '=', $id)->find();
			if ($picture->loaded())
			{
				$picture->description = $description;
				$picture->save();
			}
		}
	}
	$this->request->redirect('/admin/picture/list/'.$booklet_id);
}



}




